16. Auto-configuration(自动配置)
1 | Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database. |
Spring Boot 自动配置将根据您增加的jar包依赖关系尝试全自动的配置您的Spring应用。举个例子,如果HSQLDB在您的类路径下,而您未配置任何数据库连接beans,Spring将会自动配置一个基于内存的数据库。
1 | You need to opt-in to auto-configuration by adding |
您需要通过增加@EnableAutoConfiguration或者@SpringBootApplication注解到您的@Configuration配置类,以此来加入自动配置的功能。
1 | You should only ever add one @SpringBootApplication or |
您应该只添加@SpringBootApplication或者@EnableAutoConfiguration中的一个注解。我们一般建议您将一个或另一个添加到您的主@Configuration类。
16.1 Gradually Replacing Auto-configuration(逐渐替换自动配置)
1 | Auto-configuration is non-invasive. At any point, you can start |
自动配置是非侵入式的。 在任何时候,您都可以开始定义自己的配置以替换自动配置的特定部分。
例如,如果您添加自己的DataSource bean,则默认的嵌入式数据库支持会被取消。1
2
3
4If you need to find out what auto-configuration is currently
being applied, and why, start your application with the --debug switch.
Doing so enables debug logs for a selection of core loggers and logs
a conditions report to the console.
如果您需要了解当前正在应用的自动配置以及为什么被使用,采用–debug开关启动您的应用程序。
这样做可以启用debug断点日志作为主日志输出,记录各种条件分支报告到控制台。
16.2 Disabling Specific Auto-configuration Classes(禁用特定的自动配置类)
1 | If you find that specific auto-configuration classes that you |
如果您发现一些特殊的自动配置类,您并不想他们生效。您可以在@EnableAutoConfiguration注解中使用排除标签去禁用他们,如下例子:1
2
3
4
5
6
7
8import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
1 | If the class is not on the classpath, you can use the excludeName |
如果该类不在类路径下,您可以使用该注解的excludeName属性去定义全路径名称来替代。最后,您可以通过使用spring.autoconfigure.exclude控制自动配置的类的列表。
1 | You can define exclusions both at the annotation level and by |
你既可以在注解中定义exclusions,也可以在property属性中定义。